<template>
  <div>
    <div class="cluster-controls-container">
      <div class="control-item">
        <el-select v-model="ClusterAlgorithm" placeholder="请选择聚类算法">
          <el-option
            v-for="item in ClusterAlgorithmOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="control-item">
        <el-button icon="el-icon-plus" type="primary" @click="DialogTimePick = true">选择时间</el-button>
      </div>
      <div class="control-item">
        <el-button v-loading.fullscreen.lock="isLoading"
                   element-loading-background="rgba(0, 0, 0, 0.8)"
                   element-loading-spinner="el-icon-loading"
                   element-loading-text="拼命运算中(ง •̀_•́)ง"
                   icon="el-icon-s-data"
                   type="primary"
                   @click="handleCluster"
        >
          开始聚类
        </el-button>
      </div>
      <div class="control-item">
        <el-button v-loading.fullscreen.lock="isSaving"
                   element-loading-background="rgba(0, 0, 0, 0.8)"
                   element-loading-spinner="el-icon-loading"
                   element-loading-text="拼命保存中(ง •̀_•́)ง"
                   icon="el-icon-finished"
                   type="success"
                   @click="SaveOutCome">保存结果</el-button>
      </div>
      <div class="control-item">
        <el-button icon="el-icon-delete" type="danger" @click="clearOutCome">清空结果</el-button>
      </div>
    </div>

    <el-container class="cluster-container">
      <el-empty
        description="暂无类别，请先聚类"
        v-if="categories.length === 0"
        :image-size="300"
        class="center-empty"
      ></el-empty>
      <div class="tableData" v-else>
        <el-table
          :data="categories"
          :header-cell-style="{ background: '#f2f5fc', color: '#555555' }"
          border stripe
          style="width: 100%;"
          max-height="600px"
          :row-class-name="tableRowClassName"
        >
          <el-table-column
            label="类别名称"
            prop="category_name">
          </el-table-column>
          <el-table-column
            label="类别描述"
            prop="category_describe">
          </el-table-column>
          <el-table-column
            label="生产状况"
            prop="suggestion">
          </el-table-column>
          <el-table-column label="气流特征">
            <template v-slot="scope">
              <p>
                {{ scope.row.air_feature.map(item => item.parameter_mean).join(', ') }}
              </p>
              <p>
                {{ scope.row.air_feature.map(item => item.value).join(', ') }}
              </p>
            </template>
          </el-table-column>
          <el-table-column label="炉热特征">
            <template v-slot="scope">
              <p>
                {{ scope.row.temp_feature.map(item => item.parameter_mean).join(', ') }}
              </p>
              <p>
                {{ scope.row.temp_feature.map(item => item.value).join(', ') }}
              </p>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
              <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px;">
                <el-button size="mini" type="primary" @click="EditCategory(scope.row, scope.$index)">编辑</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-container>



    <el-dialog title="选择时间" :visible.sync="DialogTimePick" width="60%">
      <div style="text-align: center">
        <el-transfer
          style="text-align: left; display: inline-block;"
          v-model="RecordTimes"
          filterable
          filter-placeholder="请输入日期信息筛选"
          :titles="['可选数据日期', '运算数据日期']"
          :button-texts="['排除', '选中']"
          :data="TimeData">
        </el-transfer>
      </div>
    </el-dialog>

    <el-dialog title="类别特征数据" :visible.sync="DialogFeatureData" width="60%">
      <el-table :data="featureData" style="width: 100%"
                :row-class-name="tableRowClassName"
      >
        <el-table-column prop="parameter_id" label="特征ID"></el-table-column>
        <el-table-column prop="parameter_mean" label="特征名称"></el-table-column>
        <el-table-column prop="value" label="特征值"></el-table-column>
        <el-table-column prop="parameter_dimension" label="量纲"></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="编辑类别" :visible.sync="DialogEdit" width="60%" :close-on-click-modal="false">
      <el-form :model="form">
        <el-form-item label="类别名称">
          <el-input v-model="form.category_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类别特征描述">
          <el-input v-model="form.category_describe" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类别下生产状况">
          <el-input v-model="form.suggestion" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditCancel">取 消</el-button>
        <el-button type="primary" @click="new EditConfirm(indexOfCategories)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      DialogFeatureData: false,
      DialogEdit: false,
      maxColHeight: '580px',
      DialogTimePick: false,
      isLoading: false,
      isSaving:false,
      indexOfCategories: null,
      TimeData: [],
      featureData:[],
      categories:[
      ],
      ClusterAlgorithmOptions: [
        {
          value: 'GMM',
          label: '高斯混合聚类'
        },
      ],
      ClusterAlgorithm: '',
      RecordTimes: [],
      form: {
      },
      intervalId: null,
    }
  },
  methods: {
    tableRowClassName({row, rowIndex}) {
      if (rowIndex % 2 === 1) {
        return 'warning-row';
      }
    },
    resetForm(){
      this.form = {}
      // this.indexOfCategories = null
    },
    SeeFeature(featureData){
      this.DialogFeatureData = true;  // 被修复的部分
      this.featureData = featureData;
    },
    EditCategory(row, index){
      this.DialogEdit = true;
      this.form = row;
      // this.indexOfCategories = index;
    },
    EditCancel(){
      this.DialogEdit = false;
      this.resetForm()
    },
    EditConfirm() {
      this.categories[this.indexOfCategories] = this.form;
      this.$message({
        message: '修改成功',
        type: 'success'
      })
      this.DialogEdit = false;
    },
    handleDelete(index){
      this.categories.splice(index, 1)
    },
    handleCluster() {
      if(this.RecordTimes.length === 0 || this.ClusterAlgorithm === ''){
        this.$message({
          message: '请选择聚类算法和数据日期',
          type: 'error'
        })
        return;
      }
      this.isLoading = true;
      const input = {
        clusterAlgorithm: this.ClusterAlgorithm,
        recordTimes: this.RecordTimes,
        isday: true,
      };
      console.log(input)
      this.$axios.post(this.$Python +'/getCategories', input).then(res => {
        res = res.data
        console.log(res)
        if (res.code === 200) {
          this.categories = res.data
          sessionStorage.setItem('categories', JSON.stringify(res.data))
        }else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
        this.isLoading = false;
      }).catch(err => {
        this.isLoading = false;
          console.log(err);
          this.$message({
            message: '请求失败',
            type: 'error'
          })
        }
      )

    },

    SaveOutCome(){
      if(this.categories.length === 0){
        this.$message({
          message: '没有结果，请先聚类',
          type: 'error'
        })
        return;
      }
      this.isSaving = true
      this.$axios.post(this.$httpUrlCategory +'/saveCategories', this.categories).then(res => {
        res = res.data
        console.log(res)
        if (res.code === 200) {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.categories = []
          sessionStorage.removeItem('categories')
          setTimeout(() => {
            this.isSaving = false
            // ... 显示聚类结果 ...
          }, 500);
          // 重新训练预测模型
          this.acceptNewGMMModel()

        }else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }).catch(err => {
        console.log(err);
        this.$message({
          message: '请求失败',
          type: 'error'
        })
      })
    },
    acceptNewGMMModel(){
      const input = {
        clusterAlgorithm: this.ClusterAlgorithm,
        recordTimes: this.RecordTimes,
        isday: true,
      }
        this.$axios.post(this.$Python+'/acceptNewGMMModel',input).then(res => {
            res = res.data
            console.log(res)
            if (res.code === 200) {
              this.$message({
                  message: '新的GMM模型保存成功',
                  type: 'success'
              })
              this.trainAndSavePredictionModel()
            }else {
            this.$message({
                message: res.msg,
                type: 'error'
            })
            }
        }).catch(err => {
            console.log(err);
            this.$message({
            message: '请求失败',
            type: 'error'
            })
        })
    },
    trainAndSavePredictionModel(){
      const input = {
        clusterAlgorithm: this.ClusterAlgorithm,
        recordTimes: this.RecordTimes,
        isday: true,
      }
      this.$axios.post(this.$Python+'/trainAndSavePredictionModel',input).then(res => {
        res = res.data
        console.log(res)
        if (res.code === 200) {
          this.$message({
            message: '预测模型重新训练成功',
            type: 'success'
          })
        }else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }).catch(err => {
        console.log(err);
        this.$message({
          message: '请求失败',
          type: 'error'
        })
      })
    },
    clearOutCome(){
      this.$confirm('此操作将清空此次聚类结果，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.categories = []
        sessionStorage.removeItem('categories')
        this.$message({
          type: 'success',
          message: '已清空此次聚类结果'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    getRecordTime(){
      this.$axios.get(this.$httpUrlCategory +'/getRecordTime').then(res => {
        res = res.data
        console.log("获得时间数据", res)
        if (res.code === 200) {
          const times = res.data
          this.TimeData = []
          for (let i = 0; i < times.length; i++) {
            this.TimeData.push({
              label: times[i],
              key: times[i]
            })
          }
          sessionStorage.setItem('TimeData', JSON.stringify(this.TimeData))
        }else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          })
        }
      })
    }
  },
  mounted() {
    if(sessionStorage.getItem('categories')){
      this.categories = JSON.parse(sessionStorage.getItem('categories'))
    }
    if (sessionStorage.getItem('TimeData')) {
      this.TimeData = JSON.parse(sessionStorage.getItem('TimeData'))
    }else {
      this.getRecordTime()
    }
    // 每10秒轮询一次
    this.intervalId = setInterval(this.loadCategory, 10*1000);
  },
  beforeDestroy() {
    clearInterval(this.intervalId);
  }
}
</script>

<style>
.cluster-container {
  margin: 8px;
  display: flex;
  justify-content: center; /* 横向居中 */
  align-items: center; /* 纵向居中 */
}

.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 5px;
  width: 1208px;
}
.cluster-container .Cluster-card {
  flex: 0 0 calc(50% - 10px); /* 每行最多两个，减去间距 */
  max-width: calc(50% - 10px); /* 每行最多两个，减去间距 */
  height: 260px;
  width: 550px;
  margin-bottom: 10px;
  /* 其他样式不变 */
}
.cluster-controls-container {
  display: flex;
  justify-content: space-between; /* 分配组件之间的水平间距 */
  padding: 15px 20px 15px 20px;
  border-radius: 0 0 15px 15px;
  box-shadow: 0 2px 8px 2px rgba(0, 0, 0, 0.1);
}

.control-item {
  text-align: center;
  margin-right: 0px; /* 调整组件之间的具体间距，根据需要进行更改 */
}
.center-empty {
  display: flex;
  justify-content: center;
  align-items: center;
}
.tableData{
  width: 100%;
  margin: 10px;
}
.el-table-column {
  flex-grow: 1; /* 允许列根据内容自动扩展 */
}
</style>
